from fastapi import Depends, FastAPI
from funcs.lucky_draw import lucky_draw  # type: ignore
from lucky_draw_api.midware.check_token import check_token
from lucky_draw_api.models import (
    DrawFullError,
    LuckyDrawWithParam,
    NoAuthorizedError,
    ResponseData,
    SqlError,
)

app: FastAPI = FastAPI()


@app.get("/lucky_draw")
def lucky_draw_api() -> ResponseData | DrawFullError | SqlError:
    """
    抽奖

    - 返回值:
        - ResponseData: 抽中的学生的序号
        - DrawFullError: 抽奖人数已满
        - SqlError: 数据库查询错误
    """
    draw_id: int
    err: Exception | None
    draw_id, err = lucky_draw()
    if err:
        if str(err) == "抽奖人数已满":
            return DrawFullError()
        return SqlError()

    return ResponseData(data={"draw_id": draw_id})


@app.get("/lucky_draw_with_param")
def lucky_draw_with_param_api(
    params: LuckyDrawWithParam = Depends(),
) -> ResponseData | DrawFullError | SqlError | NoAuthorizedError:
    """
    get方法，带参数
    参数为token

    - 返回值
        - ResponseData: 抽中的学生的序号
        - DrawFullError: 抽奖人数已满
        - SqlError: 数据库查询错误
        - NoAuthorizedError: 未授权
    """
    if params.token == "QWEzxc123":
        draw_id: int
        err: Exception | None
        draw_id, err = lucky_draw()
        if err:
            if str(err) == "抽奖人数已满":
                return DrawFullError()
            return SqlError()

        return ResponseData(data={"draw_id": draw_id})
    else:
        return NoAuthorizedError()


@app.post("/lucky_draw_post")
def lucky_draw_post_api(
    params: LuckyDrawWithParam,
) -> ResponseData | DrawFullError | SqlError | NoAuthorizedError:
    """
    使用post方法隐藏token

    - 返回值:
        - ResponseData: 抽中的学生的序号
        - DrawFullError: 抽奖人数已满
        - SqlError: 数据库查询错误
        - NoAuthorizedError: 未授权
    """

    if params.token == "QWEzxc123":
        draw_id: int
        err: Exception | None
        draw_id, err = lucky_draw()
        if err:
            if str(err) == "抽奖人数已满":
                return DrawFullError()
            return SqlError()

        return ResponseData(data={"draw_id": draw_id})
    else:
        return NoAuthorizedError()


@app.get("/lucky_draw_with_header")
def lucky_draw_with_header_api(token: str = Depends(check_token)):
    
    draw_id: int
    err: Exception | None
    draw_id, err = lucky_draw()
    if err:
        if str(err) == "抽奖人数已满":
            return DrawFullError()
        return SqlError()

    return ResponseData(data={"draw_id": draw_id})
